<?php

namespace app\admin\controller;

use think\Request;
use app\admin\controller\Common;
use app\admin\model\Banner as BannerModel;
use think\Db;


class Banner extends Common
{

    /*图片上传*/
    public function add(){
        if(request()->isPost()){
             // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'.'/'.'banner');
            if($info){
                $filePath = DS .'uploads'.'/'.'banner'.'/'.$info->getSaveName();
                $path = str_replace("\\", "/", $filePath);
                // $count = Db::table('banner')->count();
                $data = [
                    'url' =>  $path,
                ];
                Db::table('lan_banner')->insert($data);
                $this->success('添加图片成功','lst');
            }else{
                echo $file->getError();
            }
        }
        return view();
       
}
    public function lst(){
        $banner = new BannerModel();
        $bannerres = db('banner')->select();
        $this->assign('bannerres', $bannerres);
        return view();
    }

    //删除操作
    public function delData(){
        $id = input('id');
        $this->delFile($id);
        $res = BannerModel::destroy($id);
        if ($res>0){
            return ['code' => 1, 'msg' => '轮播图删除成功'];
        }
        else{
            return ['code' => 0, 'msg' => '轮播图删除失败'];
        }
    }

    public function delFile($id){
        $file_th = db('banner')->where('id', $id)->field('url')->find();
        $al_array_new = implode($file_th);
        $file_s = $_SERVER['DOCUMENT_ROOT'].$al_array_new;
        if (file_exists($file_s)){
            @unlink($file_s);
        }
    }

    public function status(){
        $id = input('id');
        $count = db('banner')->where('status', 1)->count();
        $sh = Db::table('lan_banner')->where(['status' => 1, 'id' => $id]) -> find();
        if ($sh){
            if ($count <= 3){
                return \json(['code' => 2 , 'msg' => '达到图片最低显示']);
            }
            \db('banner')->update(['status' => 0 , 'id'=> $id]);
                return \json(['code' => 1 , 'msg' => '状态更改成功']);
        }else{
            if ($count >= 5){
                return \json(['code' => 2 , 'msg' => '达到可显示图片最多数']);
            }
            \db('banner')->update(['status' => 1 , 'id'=> $id]);
                return \json(['code' => 1 , 'msg' => '状态更改成功']);
        }
    }

    public function edit(){
        return view();
    }
}
